var fs = require("fs");
var http = require('http');
 

/**
 * Post file to server
 * @param sFileName filename
 * @param data file data
 * @param host host ip addr
 * @param port host port
 */
function PostFileToServer(sFileName, data, host,port) {
    return new Promise(function(resolve,reject){
        var boundary = "NODEJSPOSTFILE-" + (Math.random() * 9007199254740992).toString(36);
        var sHeader = "--" + boundary + "\r\n";
        sHeader += "Content-Disposition: form-data; name=\"Capsule\"; filename=\"" + sFileName + "\"\r\n";
        sHeader += "Content-Type: application/octet-stream\r\n\r\n";
        var sEndData = "\r\n--" + boundary + "--\r\n\r\n";
        var options = {
            hostname: host,
            port    : port,
            path    : "/receivecapsule",
            method  : 'POST'
        };
        var httpreq = http.request(options, function (httpres) {
            httpres.on('data', function (dataResponse) {
                var response = JSON.parse(dataResponse);
                resolve(response);
            });
        });
        httpreq.setHeader('Content-Type',   'multipart/form-data; boundary=' + boundary + '');
        httpreq.setHeader('Content-Length', Buffer.byteLength(sHeader) + data.length + Buffer.byteLength(sEndData));
        httpreq.on('error', function(e) {
            console.log('problem with request: ' + e.message);
            reject(e);
        });
        httpreq.write(sHeader);
        httpreq.write(data);
        httpreq.write(sEndData);
        httpreq.end();
    });
}

/**
 * Send capsule
 * @param path file path (string)
 * @param ipaddr server ip address (string)
 * @param host server port
 */
function SendCapsule(path,ipaddr,port){
    return new Promise(function(resolve,reject){
        fs.readFile(path, function (err, data) {
            if (err) reject(err);
            console.log(data.length);
            filename=path.split('/').pop();
            PostFileToServer(filename, data,ipaddr,port).then((value)=>{
                resolve(value);
                console.log(value);
            },
            function(error){
                reject(error)
            });
        });
    })
}

